package com.asen.commons.core.jdbc.handler;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.sql.*;

/**
 * Date
 *
 * @author Gary
 * @version 1.0
 * @date 2018-11-29
 */
public class SqlDateTypeHandler extends BaseTypeHandler<Date> {

    @Override
    public int getSqlType() {
        return Types.DATE;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Date parameter)
            throws SQLException {
        ps.setDate(i, parameter);
    }

    @Override
    public Date getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        return rs.getDate(columnName);
    }

    @Override
    public Date getNullableResult(ResultSet rs, int columnIndex)
            throws SQLException {
        return rs.getDate(columnIndex);
    }

    @Override
    public Date getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        return cs.getDate(columnIndex);
    }

    @Override
    public String toSqlValue(Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof java.util.Date) {
            String strTime = DateFormatUtils.format((java.util.Date) value, "yyyy-MM-dd HH:mm:ss");
            return "\'" + strTime + "\'";
        }

        if (value instanceof String) {
            return "\'" + value + "\'";
        }

        if (value instanceof Date[]) {
            StringBuilder sb = new StringBuilder(0);
            sb.append("(");
            for (Date s : (Date[]) value) {
                if (sb.length() > 0) {
                    sb.append(", ");
                }
                String strTime = DateFormatUtils.format(s, "yyyy-MM-dd HH:mm:ss");
                sb.append("\'" + strTime + "\'");
            }
            sb.append(")");
            return sb.toString();
        }

        if (value instanceof String[]) {
            return getSqlValue((String[]) value, true);
        }

        return "\'" + value.toString() + "\'";
    }

    @Override
    public Date getValue(Object value) throws Exception {
        if (value == null) {
            return null;
        }

        if (Date.class.isAssignableFrom(value.getClass())) {
            return (Date) value;
        }

        String[] patterns = new String[]{"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd", "yyyy-MM-dd HH:mm", "yyyy-MM-dd HH:mm"};
        return new Date(DateUtils.parseDate(value.toString(), patterns).getTime());
    }
}
